﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Cn.Edwon.Web;
using System.Reflection;
using Cn.Edwon.Web.Crud;
using Cn.Edwon.Web.Ac;
using Cn.Edwon.Web.Session;
using System.Xml;
using System.Text;
using Cn.Edwon.Web.Validation;

namespace Cn.Edwon.Web.Support {
    /// <summary>
    /// 
    /// </summary>
    public class PageSupport : System.Web.UI.Page, ICrudEventHandler,IActorSessOper {
        public static Common.Logging.ILog log = Common.Logging.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        public static readonly string ROOT = ClientHelper.RootPath;

        #region 相对于页面的全局变量

        private String _AbsolutePath;
        /// <summary>
        /// 当前页面相对于根的绝对路径
        /// </summary>
        public String AbsolutePath {
            get { return _AbsolutePath; }
            set { _AbsolutePath = value; }
        }
        
        private IAuthentication _Ac;
        /// <summary>
        /// 身份校验器
        /// </summary>
        public IAuthentication Ac {
            get { return _Ac; }
            set { _Ac = value; }
        }

        private String _RefUrl;
        /// <summary>
        /// 当前链接之前的请求链接
        /// </summary>
        public String RefUrl {
            get { return _RefUrl; }
            set { _RefUrl = value; }
        }

        /// <summary>
        /// 登录之前的请求链接，用于在登录后跳转到该页面
        /// </summary>
        public String LoginRefUrl {
            set {
                Session[ClientHelper.SESS_LOGIN_REFURL_KEY] = value;
            }
            get {
                if (Session[ClientHelper.SESS_LOGIN_REFURL_KEY] == null) {
                    if (String.IsNullOrEmpty(ClientHelper.Ac.RedirectAfterLogin))
                        return ClientHelper.RootUrl;
                    else
                        return ClientHelper.RootUrl+ClientHelper.Ac.RedirectAfterLogin;
                } else {
                    return (String)Session[ClientHelper.SESS_LOGIN_REFURL_KEY];
                }
            }
        }



        #endregion

        #region CRUD
        #region ICrudEventHandler 成员
        public void OnCrudCreateLoad(object sender, EventArgs e) {
            Crud.DoCreateLoad(sender, e);
        }

        public void OnCrudUpdateLoad(object sender, EventArgs e) {
            Crud.DoUpdateLoad(sender, e);
        }

        public void OnCrudReadLoad(object sender, EventArgs e) {
            Crud.DoReadLoad(sender, e);
        }

        public void OnCrudListLoad(object sender, EventArgs e) {
            Crud.DoListLoad(sender, e);
        }

        public void OnCrudRead(object sender, EventArgs e) {
            Crud.DoRead(sender, e);
        }

        public void OnCrudCreate(object sender, EventArgs e) {
            Crud.DoCreate(sender, e);
        }

        public void OnCrudUpdate(object sender, EventArgs e) {
            Crud.DoUpdate(sender, e);
        }

        public void OnCrudDelete(object sender, EventArgs e) {
            Crud.DoDelete(sender, e);
        }

        public void OnCrudSearch(object sender, EventArgs e) {
            Crud.DoSearch(sender, e);
        }
        #endregion
        public CrudOperation Crud;
        private void RegistCrudEvents() {
            Crud.Create += new EventHandler(OnCrudCreate);
            Crud.Delete += new EventHandler(OnCrudDelete);
            Crud.Read += new EventHandler(OnCrudRead);
            Crud.Search += new EventHandler(OnCrudSearch);
            Crud.Update += new EventHandler(OnCrudUpdate);
        }
        #endregion

        #region IActorSessOper 成员
        public ISessActor Actor {
            set { 
                Session[ClientHelper.SESS_USER_KEY] = value;
            }
            get {
                if (Session[ClientHelper.SESS_USER_KEY] == null) {
                    return null;
                } else {
                    return (ISessActor)Session[ClientHelper.SESS_USER_KEY];
                }
            }
        }

        public void ClearActor() {
            log.Debug("清除session");
            Session[ClientHelper.SESS_USER_KEY] = null;
            Session.Remove(ClientHelper.SESS_USER_KEY);
        }
        /// <summary>
        /// 属主Key
        /// </summary>
        public String OwnerKey {
            get {
                if (this.Actor != null) {
                    return this.Actor.OwnerKey;
                } else {
                    return SupportUtil.OWNER_KEY_DEFAULT;
                }
            }
        }

        public UserPower Power {
            get {
                if (this.Actor != null) {
                    return this.Actor.Power;
                } else {
                    return new UserPower();
                }
            }
        }

        #endregion

        #region Validation
        /// <summary>
        /// 注册表单验证的脚本
        /// </summary>
        private void BuildValidationScript() {
            try {
                Page.ClientScript.RegisterStartupScript(Page.GetType(), Request.Url.AbsoluteUri, QuickValidator.Build2Json(_AbsolutePath), true);
            } catch (Exception ex) {
                log.Error("构造validation脚本时出现错误", ex);
                return;
            }
        }
        #endregion

        #region 处理远程认证
        private void RemoteAcHandler() {
            String racUser = Request.QueryString["racuser"];
            String racKey = Request.QueryString["rackey"];
            if (String.IsNullOrEmpty(racUser) || String.IsNullOrEmpty(racKey)) return;
            if (this.Actor != null && this.Actor.ID == racUser) return;
        }
        #endregion

        /// <summary>
        /// 重写页面初始化
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e) {
            base.OnInit(e);
            //获取当前页面相对于根的绝对路径
            _AbsolutePath = ClientHelper.IdentyUri(Request.Url.ToString());
            
            //获取前一个链接请求地址
            _RefUrl = "";
            if (!Page.IsPostBack && !Page.IsCallback && Request.UrlReferrer != null) {
                _RefUrl = Request.UrlReferrer.ToString();
            }

            //页面验证模块
            if (ClientHelper.Ac.Enable) {
                _Ac = ClientHelper.CreateAc();
                
                //远程校验
                //String racUser = Request.QueryString["racuser"];
                //String racKey = Request.QueryString["rackey"];
                //if (!String.IsNullOrEmpty(racUser) && !String.IsNullOrEmpty(racKey)) {
                //    if (this.Actor == null || this.Actor.ID != racUser) {
                //        Actor = _Ac.RemoteHandler(Request.QueryString["racuser"], Request.QueryString["rackey"]);
                //    }
                //}

                _Ac.Actor = Actor;
                String _url = Request.Url.ToString();
                String _page = Request.Url.AbsolutePath;
                
                //不验证登录页
                String _loginUrl = ClientHelper.RootUrl + ClientHelper.Ac.LoginUrl;
                Uri _loginUri = new Uri(_loginUrl);
                String _loginPage = (_loginUri == null) ? _loginUrl : _loginUri.AbsolutePath.ToLower();
                
                //不验证PowerLow页
                String _powerLowUrl = ClientHelper.RootUrl + ClientHelper.Ac.PowerLowUrl;
                Uri _powerLowUri = new Uri(_powerLowUrl);
                String _powerLowPage = (_powerLowUri == null) ? _powerLowUrl : _powerLowUri.AbsolutePath.ToLower();

                if ((_url.ToLower().IndexOf(_loginPage) == -1)
                    && (_url.ToLower().IndexOf(_powerLowPage) == -1)) {//如果不是登录页和powerlow页面
                    AcState _state = _Ac.Authenticate(_url);//校验页面
                    if (_state == AcState.SessionLost) {
                        log.Debug("Authentication false:Session Lost,Redirect to :" + _loginUrl);
                        Response.Redirect(_loginUrl,true);
                        return;
                    } else if (_state == AcState.PowerLow) {
                        log.Debug("Authentication false:Power low,Redirect to :" + _powerLowUrl);
                        String _parm = _AbsolutePath;
                        String _newUrl = (_powerLowUrl.IndexOf("?") == -1) ? (_powerLowUrl + "?" + _parm) : ((_powerLowUrl + "&" + _parm));
                        Response.Redirect(_newUrl, true);
                        return;
                    }
                }
            }
            
            //CRUD模块
            if (ClientHelper.CrudEnable) {
                Crud = new CrudOperation(Page);
                RegistCrudEvents();
            }

            //表单验证模块
            if (ClientHelper.VdEnable) {
                BuildValidationScript();
            }


        }

    }
}
